{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 3,
   "metadata": {},
   "outputs": [
    {
     "ename": "KeyboardInterrupt",
     "evalue": "",
     "output_type": "error",
     "traceback": [
      "\u001b[1;31m---------------------------------------------------------------------------\u001b[0m",
      "\u001b[1;31mKeyboardInterrupt\u001b[0m                         Traceback (most recent call last)",
      "\u001b[1;32m<ipython-input-3-f577a35ab478>\u001b[0m in \u001b[0;36m<module>\u001b[1;34m()\u001b[0m\n\u001b[0;32m      5\u001b[0m \u001b[1;32mwhile\u001b[0m \u001b[1;32mTrue\u001b[0m\u001b[1;33m:\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      6\u001b[0m     \u001b[1;31m#从摄像头读取图片\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[1;32m----> 7\u001b[1;33m     \u001b[0msucess\u001b[0m\u001b[1;33m,\u001b[0m\u001b[0mimg\u001b[0m\u001b[1;33m=\u001b[0m\u001b[0mcap\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mread\u001b[0m\u001b[1;33m(\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0m\u001b[0;32m      8\u001b[0m     \u001b[1;31m#转为灰度图片\u001b[0m\u001b[1;33m\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n\u001b[0;32m      9\u001b[0m     \u001b[0mgray\u001b[0m\u001b[1;33m=\u001b[0m\u001b[0mcv2\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mcvtColor\u001b[0m\u001b[1;33m(\u001b[0m\u001b[0mimg\u001b[0m\u001b[1;33m,\u001b[0m\u001b[0mcv2\u001b[0m\u001b[1;33m.\u001b[0m\u001b[0mCOLOR_BGR2GRAY\u001b[0m\u001b[1;33m)\u001b[0m\u001b[1;33m\u001b[0m\u001b[0m\n",
      "\u001b[1;31mKeyboardInterrupt\u001b[0m: "
     ]
    }
   ],
   "source": [
    "import numpy as np\n",
    "import cv2\n",
    "#调用笔记本内置摄像头，所以参数为0，如果有其他的摄像头可以调整参数为1，2\n",
    "cap=cv2.VideoCapture(0)\n",
    "while True:\n",
    "    #从摄像头读取图片\n",
    "    sucess,img=cap.read()\n",
    "    #转为灰度图片\n",
    "    gray=cv2.cvtColor(img,cv2.COLOR_BGR2GRAY)\n",
    "    #显示摄像头，背景是灰度。\n",
    "    cv2.imshow(\"img\",gray)\n",
    "    #保持画面的持续。\n",
    "    k=cv2.waitKey(1)\n",
    "    if k == 27:\n",
    "        #通过esc键退出摄像\n",
    "        cv2.destroyAllWindows()\n",
    "        break\n",
    "    elif k==ord(\"s\"):\n",
    "        #通过s键保存图片，并退出。\n",
    "        cv2.imwrite(\"image2.jpg\",img)\n",
    "        cv2.destroyAllWindows()\n",
    "        break\n",
    "#关闭摄像头\n",
    "cap.release()\n"
   ]
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.6.2"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 2
}
